import requests
import time
import hashlib
import hmac
import operator
import json

class RefreshAccessToken:
    def __init__(self, app_key, app_secret, access_token, refresh_token):
        self.app_key = app_key
        self.app_secret = app_secret
        self.refresh_token = refresh_token
        self.base_url = "https://gw.superboss.cc/router"
        self.access_token = access_token

    def generate_signature(self, params, sign_method="hmac"):
        """
        生成签名（与您提供的示例一致）
        :param params: 参数字典
        :param sign_method: 签名方法，支持md5/hmac/hmac-sha256
        :return: 签名字符串
        """
        # 移除sign参数、byte[]类型的参数以及值为null的参数
        params = {k: v for k, v in params.items() if v is not None and k != 'sign'}

        # 根据参数名称的ASCII码表的顺序排序
        sorted_params = sorted(params.items(), key=operator.itemgetter(0))

        # 将排序好的参数名和参数值拼装在一起
        str_params = "".join(["{}{}".format(k, v) for k, v in sorted_params])
        print('sign_str:' + str_params)  # 调试用，可看到签名字符串

        if sign_method == 'md5':
            m = hashlib.md5()
            m.update((self.app_secret + str_params + self.app_secret).encode('utf-8'))
            return m.hexdigest()
        elif sign_method == 'hmac':
            h = hmac.new(self.app_secret.encode('utf-8'), str_params.encode('utf-8'), digestmod=hashlib.md5)
            return h.hexdigest()
        elif sign_method == 'hmac-sha256':
            h = hmac.new(self.app_secret.encode('utf-8'), str_params.encode('utf-8'), digestmod=hashlib.sha256)
            return h.hexdigest()
        else:
            raise ValueError("Unsupported sign method: " + sign_method)

    def call_api(self, method, api_params=None, sign_method="hmac"):
        """
        调用API接口
        :param method: API方法名
        :param api_params: API业务参数
        :param sign_method: 签名方法
        :return: API响应结果
        """
        if api_params is None:
            api_params = {}

        # 公共参数
        common_params = {
            "method": method,
            "appKey": self.app_key,
            "timestamp": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
            "format": "json",
            "version": "1.0",
            "sign_method": sign_method,
            "session": self.access_token
        }
        # 合并参数
        all_params = {**common_params, **api_params}
        json_print(all_params)
        # 生成签名
        sign = self.generate_signature(all_params, sign_method)
        all_params["sign"] = sign
        # 发送请求
        headers = {
            "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
        }

        response = requests.post(self.base_url, data=all_params, headers=headers)
        return response.json()

    def get_accesstoken(self):
        """
        查询商品分类
        :return: API响应结果
        """
        params = {}
        params['refreshToken'] = self.refresh_token
        return self.call_api("open.token.refresh", params)


def json_print(input_json):
    print(json.dumps(input_json, indent=4, ensure_ascii=False))

# 使用示例
if __name__ == "__main__":
    APP_KEY = ""
    APP_SECRET = ""
    ACCESS_TOKEN = ""
    REFRESH_TOKEN = ""

    # API调用示例
    print("=== API调用 ===")
    api = RefreshAccessToken(APP_KEY, APP_SECRET, ACCESS_TOKEN, REFRESH_TOKEN)
    result = api.get_accesstoken()
    json_print(result)
    # 发送通知
    requests.get(f"https://api.day.app/???/{result}")

    # print("失效日期", result['session']['expiresIn'])

